import React from 'react';
import {
  Form,
  Input,
  Button,
  message,
  Modal,
  Checkbox,
  InputNumber,
  Space,
  Tabs,
  DatePicker,
  Upload,
  Select,
  Col,
} from 'antd';
import { ExclamationCircleOutlined, LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { connect } from 'umi';
import UploadUtil from '@/components/UploadUtil';
import moment from 'moment';

const currControl = 'Advertisement';
const { confirm } = Modal;
const { TabPane } = Tabs;

class CourseEdit extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      loading: false,
      datas: {},
      imageUrl: '',
      imgList: [],
    };
  }
  formRef: any = React.createRef();
  componentDidMount() {
    const { ParentData } = this.props;
    if (ParentData && ParentData.id) {
      this.getData(ParentData.id);
    }
  }
  getData = (id: number) => {
    const { dispatch } = this.props;
    if (id) {
      dispatch({
        type: 'Abp/get',
        payload: { id },
        control: currControl,
      }).then(() => {
        var result = this.props.response.result;
        if (result.advPic) {
          this.setState({ imageUrl: result.advPic });
        }
        if (result.endTime) result.endTime = moment(result.endTime);
        if (result.startTime) result.startTime = moment(result.startTime);
        this.formRef.current.setFieldsValue({ model: result });
      });
    }
  };
  onFinish = async (values: any) => {
    var act = 'Abp/create';
    if (values.model.id) {
      act = 'Abp/update';
    }
    if (this.state.imageUrl) {
      values.model.advPic = this.state.imageUrl;
    }
    values.model.endTime = values.model.endTime?.format('YYYY-MM-DD');
    values.model.startTime = values.model.startTime?.format('YYYY-MM-DD');
    this.props
      .dispatch({
        type: act,
        payload: values.model,
        control: currControl,
      })
      .then(() => {
        var resp = this.props.response;
        if (resp.success) {
          message.success('保存成功！');
          this.props.fetchDatas();
        } else {
          message.error('保存错误，请联系管理员');
        }
      });
  };
  ResetForm = () => {
    var data = {
      id: 0,
    };
    this.setState({ datas: data });
    this.formRef.current.resetFields();
  };
  handleDel = () => {
    this.props
      .dispatch({
        type: 'Abp/delete',
        payload: { Id: this.state.datas.id },
        control: currControl,
      })
      .then(() => {
        var resp = this.props.response;
        if (resp.success) {
          message.success('删除成功！');
          this.props.fetchDatas();
          this.formRef.current.resetFields();
        } else {
          message.error('删除错误，请联系管理员！');
        }
      });
  };
  showConfirm = () => {
    var _this = this;
    confirm({
      title: '警告',
      icon: <ExclamationCircleOutlined />,
      content: '删除后将不可恢复，确定删除？',
      onOk() {
        _this.handleDel();
      },
      onCancel() {},
    });
  };
  handleChange = (editorState: any) => {
    this.setState({
      contentEditor: editorState.toHTML(),
    });
  };
  onChange = (value: number[]) => {
    this.setState({
      inputValue: value,
    });
  };
  handleUpload = (info: any) => {
    if (info.file.status === 'done' && info.file.response) {
      this.setState({
        imageUrl: info.file.response.result,
      });
    }
  };
  render() {
    const { datas, imageUrl, loading } = this.state;
    const uploadButton = (
      <div>
        {loading ? <LoadingOutlined /> : <PlusOutlined />}
        <div className="ant-upload-text">上传图片</div>
      </div>
    );
    return (
      <div>
        <Form ref={this.formRef} layout="vertical" onFinish={this.onFinish}>
          <Tabs defaultActiveKey="1">
            <TabPane tab="基本" key="1">
              <div style={{ display: 'none' }}>
                <Form.Item label="id" name={['model', 'id']}>
                  <Input />
                </Form.Item>
                <Form.Item label="id" name={['model', 'advPic']}>
                  <Input />
                </Form.Item>
              </div>
              <Col span={14}>
                <Form.Item
                  name={['model', 'advName']}
                  label="广告名称"
                  rules={[{ required: true, message: '请输入广告名称' }]}
                >
                  <Input />
                </Form.Item>
              </Col>
              <Col span={24}>
                <Form.Item style={{ marginBottom: 0 }}>
                  <Input.Group compact>
                    <Form.Item
                      name={['model', 'startTime']}
                      label="开始日期"
                      rules={[{ required: true, message: '请输入开始日期' }]}
                    >
                      <DatePicker style={{ width: 220 }} />
                    </Form.Item>
                    <Form.Item
                      name={['model', 'endTime']}
                      label="截至日期"
                      rules={[{ required: true, message: '请输入截至日期' }]}
                    >
                      <DatePicker style={{ width: 215 }} />
                    </Form.Item>
                  </Input.Group>
                </Form.Item>
              </Col>
              <Col span={14}>
                <Form.Item name={['model', 'linkUrl']} label="链接地址">
                  <Input />
                </Form.Item>
              </Col>
              <Col span={14}>
                <Form.Item style={{ marginBottom: 0 }}>
                  <Input.Group compact>
                    <Form.Item name={['model', 'advType']} label="广告类型">
                      <Select style={{ width: 120 }}>
                        <Select.Option value="video">视频</Select.Option>
                        <Select.Option value="pictxt">图文</Select.Option>
                      </Select>
                    </Form.Item>
                    <Form.Item name={['model', 'price']} label="广告价格">
                      <InputNumber min={0} step={0.1} style={{ width: 120 }} />
                    </Form.Item>
                    <Form.Item name={['model', 'beans']} label="购买币">
                      <InputNumber min={0} step={5} style={{ width: 120 }} />
                    </Form.Item>
                  </Input.Group>
                </Form.Item>
              </Col>
              <Col span={14}>
                <Form.Item
                  name={['model', 'place']}
                  label="广告位置"
                  rules={[{ required: true, message: '请选择广告位置' }]}
                >
                  <Input />
                </Form.Item>
              </Col>
              <Col span={14}>
                <Form.Item style={{ marginBottom: 0 }}>
                  <Input.Group compact>
                    <Form.Item name={['model', 'isEnable']} valuePropName="checked">
                      <Checkbox>有效</Checkbox>
                    </Form.Item>
                    <Form.Item name={['model', 'isFree']} valuePropName="checked">
                      <Checkbox>免费</Checkbox>
                    </Form.Item>
                  </Input.Group>
                </Form.Item>
              </Col>
            </TabPane>
            <TabPane tab="图片" key="2">
              <Form.Item>
                <Upload
                  action={UploadUtil.actionURL}
                  headers={{
                    Authorization: UploadUtil.accessToken,
                  }}
                  data={{
                    objectId: datas.id,
                    objectName: currControl,
                    objectField: 'advPic',
                  }}
                  name="files"
                  listType="picture-card"
                  className="avatar-uploader"
                  showUploadList={false}
                  beforeUpload={UploadUtil.beforeUpload}
                  onChange={this.handleUpload}
                >
                  {imageUrl ? (
                    <img
                      src={UploadUtil.imgServ + imageUrl}
                      style={{ width: '100%', height: '100%' }}
                    />
                  ) : (
                    uploadButton
                  )}
                </Upload>
              </Form.Item>
            </TabPane>
          </Tabs>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" loading={this.state.loading}>
                确定
              </Button>
              <Button onClick={this.ResetForm}>重设</Button>
              <Button danger onClick={this.showConfirm} disabled={!datas.id}>
                删除
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </div>
    );
  }
}
export default connect(({ Abp, Category }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
  Category,
}))(CourseEdit);
